package com.itheima.admin.task;

import com.itheima.admin.service.WemediaNewsAutoScanSevice;
import com.itheima.common.vo.ResultVo;
import com.itheima.wemedia.dto.WmNewsPageReqDto;
import com.itheima.wemedia.feign.WmNewsFeign;
import com.itheima.wemedia.vo.WmNewsVo;
import com.xxl.job.core.biz.model.ReturnT;
import com.xxl.job.core.handler.annotation.XxlJob;
import com.xxl.job.core.log.XxlJobLogger;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * @version 1.0
 * @description 说明
 * @package com.itheima.admin.task
 */
@Component
@Slf4j
public class SyncArticleTask {


    @Autowired
    private WmNewsFeign wmNewsFeign;

    @Autowired
    private WemediaNewsAutoScanSevice wemediaNewsAutoScanSevice;

    @XxlJob("syncArticleTask")
    public ReturnT<String> syncArticleJob(String param) {
        log.info("开始执行同步文章任务: param={}", param);
        //远程调用查询文章
        WmNewsPageReqDto dto = new WmNewsPageReqDto();
        dto.setEndPubDate(new Date());
        ResultVo<List<WmNewsVo>> listResultVo = wmNewsFeign.syncArticleTask(dto);
        //如果远程调用失败
        if (!listResultVo.isSuccess()) {
            log.error("远程调用自媒体微服务查询文章信息失败");
            XxlJobLogger.log("远程调用自媒体微服务查询文章信息失败");
        }
        //如果远程调用成功
        List<WmNewsVo> wmNewsVoList = listResultVo.getData();
        int size = wmNewsVoList.size();
        if (size > 0) {
            log.info("远程调用查询到{}：篇文章", size);
            XxlJobLogger.log("远程调用查询到{}：篇文章", size);
            for (WmNewsVo wmNewsVo : wmNewsVoList) {
                Boolean aBoolean = wemediaNewsAutoScanSevice.syncArticleTask(wmNewsVo);
                if (aBoolean){
                    log.info("同步文章数据成功{}",wmNewsVo.getId());
                    XxlJobLogger.log("同步文章数据成功{}",wmNewsVo.getId());
                }else {
                    log.info("同步文章数据失败{}",wmNewsVo.getId());
                    XxlJobLogger.log("同步文章数据失败{}",wmNewsVo.getId());
                }
            }
        }

        log.info("同步文章任务完成: param={}", param);
        return ReturnT.SUCCESS;

    }
}
